package nl.justobjects.pushlet.wrapper;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.ObjectMessage;
import javax.jms.Session;

import nl.justobjects.pushlet.core.Event;
import nl.justobjects.pushlet.pushmanager.PushManager.PushManageCommand;

import org.springframework.jms.support.converter.MessageConversionException;
import org.springframework.jms.support.converter.MessageConverter;
import org.springframework.jms.support.converter.SimpleMessageConverter;


public class EventConvert implements MessageConverter{

	private static final String IS_EVENT = "b_i_e";
	private static final String IS_PUSHMANAGE_COMMAND = "b_i_pm_c";
	
	private SimpleMessageConverter converter;

    public void setConverter(SimpleMessageConverter converter) {
        this.converter = converter;
    }
	
	@Override
	public Object fromMessage(Message message) throws JMSException, MessageConversionException {
		if (message.getBooleanProperty(IS_EVENT)) {
			Event event = (Event) ((ObjectMessage) message).getObject();
			return event;
		} else if (message.getBooleanProperty(IS_PUSHMANAGE_COMMAND)) {
			PushManageCommand command = (PushManageCommand) ((ObjectMessage) message).getObject();
			return command;
		}
		return message;
	}

	@Override
	public Message toMessage(Object object, Session session) throws JMSException,
			MessageConversionException {
		if (object instanceof Event) {
			Message message = this.converter.toMessage(object, session);
			message.setBooleanProperty(IS_EVENT, true);
			return message;
		} else if (object instanceof PushManageCommand) {
			Message message = this.converter.toMessage(object, session);
			message.setBooleanProperty(IS_PUSHMANAGE_COMMAND, true);
			return message;
		}
		return (Message) object;
	}

}
